<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="6">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="15" :xl="18">
            <el-input v-model="filterText" placeholder="名称" clearable />
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="9" :xl="6">
            <el-button :icon="isExpand ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" @click="handleExpand(isExpand ? false : true)">
              {{ isExpand ? '折叠' : '展开' }}
            </el-button>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px">
          <el-tree
            ref="deptTreeRef"
            :data="data"
            node-key="id"
            highlight-current
            :props="{ label: 'name', value: 'id' }"
            :default-expand-all="isExpand"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </el-row>
      </el-col>
      <el-col :span="18">
        <Right :dept-id="defaultDeptId" :dept-list="data" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import deptApi from '@/api/sys/dept'
import Right from './component/right.vue'

export default {
  components: { Right },
  data() {
    return {
      data: [],
      filterText: '',
      isExpand: true,
      defaultDeptId: 0
    }
  },
  // 监听过滤文本变化
  watch: {
    filterText(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$refs.deptTreeRef.filter(newVal)
      }
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    // 获取树形数据
    getTreeData() {
      deptApi.getList({}).then((res) => {
        this.data = res.data
      })
    },

    // 节点选中
    handleNodeClick(row) {
      this.defaultDeptId = row.id
    },

    // 节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.includes(value)
    },

    // 展开/折叠
    handleExpand(status) {
      this.isExpand = status
      const nodes = this.$refs.deptTreeRef.store._getAllNodes()
      for (let i = 0; i < nodes.length; i++) {
        nodes[i].expanded = status
      }
    }
  }
}
</script>
